package com.beidouapp.mvc;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.beidouapp.cache.impl.RedisDefaultAppCacheHelper;
import com.beidouapp.common.contant.SecurityContant;
import com.beidouapp.common.util.SystemConfig;
import com.beidouapp.domain.pojo.ChinaData;
import com.beidouapp.domain.pojo.MonthlySummary;
import com.beidouapp.domain.pojo.PrjProgressSummary;
import com.beidouapp.domain.pojo.StatisData;
import com.beidouapp.exception.BusinessException;
import com.beidouapp.security.model.ReturnDataInfo;
import com.beidouapp.service.EngineerService;
import com.beidouapp.service.MonthlySummaryService;
import com.beidouapp.service.ProjectService;
import com.beidouapp.translator.TranslatorManager;

/**
 *   首页Controller
 */
@Controller
@RequestMapping(value = "/index")
public class IndexController {

    private static Logger logger = LoggerFactory.getLogger(IndexController.class);
    @Autowired
    MonthlySummaryService monthlySummaryService;
    @Autowired
    private EngineerService engineerService;
    @Autowired
    private RedisDefaultAppCacheHelper redisCache;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private TranslatorManager translatorManager;
    static String CHINA_STATIS_KEY="_CHINA_STATIS_KEY";
    static  long  EXPIRE_TIME=15;
    
    
    @RequestMapping(value = "/getMonthlyDataStatis", method = RequestMethod.GET )
    public
    @ResponseBody
    ReturnDataInfo<MonthlySummary> getMonthlyDataStatis(HttpServletRequest request ) {
        try {
            List<MonthlySummary> monthlySummaries=monthlySummaryService.getAllMonthlyDataStatis();
            return ReturnDataInfo.createSuccessfulExecuteResults(monthlySummaries);
        } catch (Exception ex) {
        	logger.error("错误："+ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }
    /**
     *  
     *  首页工程师位置分布图
     *  
     */
    @RequestMapping(value = "/showEngineerPos", method = RequestMethod.GET)
    public ModelAndView showEngineerPosition(HttpSession session) {
        ModelAndView view = new ModelAndView();
        Map<String, Object>  totalMap=  engineerService.getDistributeTotal();
        view.addObject("engineerTotal", totalMap.get("ENGINEER_TOTAL"));
        view.addObject("projectTotal", totalMap.get("PROJECT_TOTAL"));
        view.setViewName("engineer/engineer_position");
        return view;
    }
    /**
	 * 获取全国省市统计数据
	 * 
	 */
	@RequestMapping(value = "/getChinaAllEngineerData", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<ChinaData> getChinaAllEngineerData(HttpSession session, HttpServletRequest request) {
        try {
        	@SuppressWarnings("unchecked")
			/*List<ChinaData> chinaDatas= (List<ChinaData>) redisCache.getCacheValue(SecurityContant.CHINA_NAMESPACE, CHINA_STATIS_KEY);
        	if(null==chinaDatas){*/
        	List<ChinaData>	chinaDatas=engineerService.getChinaAllEngineerDataList();
        		/*if(null==chinaDatas){
        			throw new BusinessException("获取全国统计数据为空！");
        		}*/
        	//redisCache.addCache(SecurityContant.CHINA_NAMESPACE, CHINA_STATIS_KEY, chinaDatas,EXPIRE_TIME , TimeUnit.MINUTES);
        	/*}*/
            return ReturnDataInfo.createSuccessfulExecuteResults(chinaDatas);
        } catch (Exception ex) {
        	logger.error("获取全国数据异常！",ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }
	@RequestMapping(value = "/showMonthlyDatasChart", method = RequestMethod.GET)
    public ModelAndView showMonthlyDatasChart(HttpSession session) {
        ModelAndView view = new ModelAndView();
        Map<String, Object>  totalMap=  engineerService.getDistributeTotal();
        view.addObject("engineerTotal", totalMap.get("ENGINEER_TOTAL"));
        view.addObject("projectTotal", totalMap.get("PROJECT_TOTAL"));
        view.setViewName("engineer/monthly_chart");
        return view;
    }
	/**
     * 
     * 获取省份列表数据
     * 
     */
    @SuppressWarnings("unchecked")
	@RequestMapping(value = "/getProvinceDataList", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<StatisData> getProvinceDataList(HttpSession session, HttpServletRequest request, @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") Integer offset, @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") Integer limit, @RequestParam(value = "globalSearch", required = false, defaultValue = "{}") String globalSearch) {
        try {
            Map paramters = new HashMap();
            if (globalSearch != null) {
                JSONObject jsonObject = JSONObject.fromObject(globalSearch);
                paramters.putAll(jsonObject);
            }
            paramters.putAll(request.getParameterMap());
            List<StatisData> engineers = engineerService.findStatisDataListByMap(paramters, offset, limit);
            Integer totalCount = engineerService.findStatisDataCountByMap(paramters);
             return ReturnDataInfo.createSuccessfulExecuteResults(engineers, offset, limit, totalCount.longValue());
        } catch (Exception ex) {
            logger.error("获取省份用户列表失败", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }
    /**
	 * 获取城市列表数据
	 * 
	 */
	@SuppressWarnings({ "unchecked", "unchecked" })
	@RequestMapping(value = "/getCityDataList", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<StatisData> getCityDataList(HttpSession session, HttpServletRequest request, @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") Integer offset, @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") Integer limit, @RequestParam(value = "globalSearch", required = false, defaultValue = "{}") String globalSearch) {
        try {
            Map paramters = new HashMap();
            if (globalSearch != null) {
                JSONObject jsonObject = JSONObject.fromObject(globalSearch);
                paramters.putAll(jsonObject);
            }
            paramters.putAll(request.getParameterMap());
            List<StatisData> engineers = engineerService.getStatisCityDataByMap(paramters, offset, limit);
            Integer totalCount = engineerService.findStatisCityDataCountByMap(paramters);
             return ReturnDataInfo.createSuccessfulExecuteResults(engineers, offset, limit, totalCount.longValue());
        } catch (Exception ex) {
            logger.error("获取城市用户列表失败", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }
	@RequestMapping(value = "/listPrjProgressSummary", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<PrjProgressSummary>   listPrjProgressSummary(){
        try{
            List<PrjProgressSummary>  datas=projectService.listPrjProgressSummary();
            return ReturnDataInfo.createSuccessfulExecuteResults(this.translatorManager.translate(datas));

        } catch (Exception ex) {
            logger.error("", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }
	
	static{
		String expireTime=SystemConfig.getConfig("experiTime");
		if(StringUtils.isNotBlank(expireTime)){
			EXPIRE_TIME=Long.valueOf(expireTime);
			logger.info("缓存失效时间："+EXPIRE_TIME+"分钟");
		}
	}

}
